<template>
  <div class="motorSelection">
    <!-- 公用表头组件 -->
    <el-card class="box-card">
      <CommonForm />
    </el-card>
    <!-- 公共导航 -->
    <el-card>
      <NavTab />
    </el-card>

    <el-card class="box-card">
      <div class="text item">
        <el-form ref="form" inline="true" :model="form">
          <el-form-item label="设备编号" style="margin-right: 20px">
            <el-input v-model="form.EQUIPMENT_ID" class="num_input" width="400px" />
          </el-form-item>
          <el-form-item label="设备类型" prop="EQUIPMENT_TYPE" style="margin-right: 20px">
            <!-- <el-cascader v-model="form.EQUIPMENT_TYPE" clearable :options="options" :show-all-levels="false" /> -->
            <el-cascader v-model="form.EQUIPMENT_TYPE" clearable :options="options" :props="{ checkStrictly: true }" :show-all-levels="false" />
          </el-form-item>
          <el-form-item style="display: inline-block; margin-right: 20px">
            <el-button @click="resetForm('form')">
              <vui-icon icon="refresh-line" />
              重置
            </el-button>
            <el-button type="primary" @click="handleQuery()">
              <vui-icon icon="search-2-line" />
              查询
            </el-button>
          </el-form-item>
        </el-form>
        <!-- 表格-->
        <div style="display: flex; justify-content: flex-end; margin-bottom: 6px; margin-right: 6px">
          <el-button v-show="showData" :disabled="tableDataInfo && tableDataInfo.length == 0" type="primary" @click="handlePublishData">
            发布数据
          </el-button>
          <el-button v-show="showData1" :disabled="tableDataInfo && tableDataInfo.length == 0" type="danger" @click="open">撤消发布</el-button>
        </div>
        <el-table
          ref="tableDataInfo"
          border
          :cell-style="{ textAlign: 'center' }"
          :data="tableDataInfo"
          :header-cell-style="{ textAlign: 'center' }"
          highlight-current-row
          :row-style="rowStyle"
          style="width: 100%"
          tooltip-effect="dark"
          @row-click="selectRow"
        >
          <el-table-column label="设备编号" prop="EQUIPMENT_ID" />
          <el-table-column label="设备类型" prop="E_TYPE_NAME" />
          <el-table-column label="长(固定端)(mm)" prop="LENGTH" />
          <el-table-column label="有效宽度(mm)" prop="WIDTH" />
          <el-table-column label="高度(mm)" prop="HEIGHT" />
          <el-table-column label="线速度(m/min)" prop="LINEAR_VELOCITY" />
          <el-table-column label="电机功率(KW)" prop="MOTOR_POWER" />
          <el-table-column label="电机选择" width="100">
            <template #default="{ row }">
              <el-button v-if="row.MOTOR_NAME || row.EQUIPMENT_MODEL" :disabled="!showData" type="text" @click="handleClick(row)">
                {{ row.MOTOR_NAME }}
              </el-button>
              <el-button v-else :disabled="!showData" type="primary" @click="handleClick(row)">
                <i class="ri-add-line" />
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="MOTOR_PRICE">
            <template #default="scope">
              <span>{{ Math.floor(scope.row.MOTOR_PRICE * 100) / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template #default="{ row }">
              <el-button :disabled="!showData" type="primary" @click="handleSure(row)">
                <vui-icon icon="save-line" />
                保存
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 模态框 -->
    <el-dialog v-model="showDialog" title="选择电机" width="80%">
      <!-- 表单 -->
      <el-form ref="formInfo" class="formInfo" inline="true" label-width="80px" :model="formInfo">
        <el-form-item label="品牌" style="margin-right: 20px; width: 320px">
          <el-select v-model="formInfo.BRAND_ID" filterable :loading="loading" placeholder="请输入关键词">
            <el-option v-for="(item, index) in brandList" :key="index" :label="item.BRAND_NAME" :value="item.BRAND_ID" />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-right: 20px; margin-left: 30px">
          <el-button @click="resetForm('form')">
            <vui-icon icon="refresh-line" />
            重置
          </el-button>
          <el-button type="primary" @click="handleQueryTable()">
            <vui-icon icon="search-2-line" />
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table
        ref="multipleTableData"
        border
        :cell-style="{ textAlign: 'center' }"
        :data="gridData"
        :header-cell-style="{ textAlign: 'center' }"
        highlight-current-row
        style="width: 100%"
        tooltip-effect="dark"
        @row-click="rowClick"
      >
        <el-table-column label width="35">
          <template #default="{ row }">
            <el-radio v-model="radioId" :label="row.EQUIPMENT_ID">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="品牌" prop="BRAND_NAME" width="200" />
        <el-table-column label="规格型号" prop="EQUIPMENT_MODEL" width="300" />
        <el-table-column label="线速度(m/min)" prop="LINEAR_VELOCITY" width="200" />
        <el-table-column label="电机功率(KW)" prop="MOTOR_POWER" width="260" />
        <el-table-column label="单价" prop="PRICE_UNTAX" width="200" @keyup="onChange" />
      </el-table>

      <div style="margin-top: 50px; margin-bottom: 30px">
        <p class="tip">
          <i class="el-icon-info" style="color: #0066ff" />
          若本次选择的品牌有折扣，则在下方输入折扣比例，如：8折，则下方输入0.8
        </p>
        <p style="display: flex; align-items: center; margin-top: 20px">
          <span style="width: 80px">品牌折扣</span>
          <el-input v-model="formInfo.MOTOR_DISCOUNT" class="num_input1" clearable @keyup="onChange" />
        </p>
      </div>
      <div style="display: flex; justify-content: center; margin-top: 10px">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button :disabled="disabledBtn" type="primary" @click="handleShowDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { defineComponent } from 'vue'
  import { getList } from '../api/home.js'
  import { GFCD } from '@/utils/utils'
  import CommonForm from '@/project/bqms/components/ComTable.vue'
  import NavTab from '@/project/bqms/components/NavTab.vue'
  export default defineComponent({
    name: 'MotorSelection',
    components: {
      CommonForm,
      NavTab,
    },
    data() {
      return {
        // budgetUnit,
        disabled2: false,
        multipleTable: [],
        multipleTableData: {},
        motorSelection: true,
        dialogVisible1: false,
        dialogVisible: false,
        showDialog: false,
        showData: true,
        disabled: true,
        // disabledTable: false,
        showData1: false,
        disabledBtn: false,
        show: false, //模态框显示
        code: '',
        form: {
          EQUIPMENT_ID: '',
          EQUIPMENT_TYPE: [],
          TYPE_NAME: '',
          TYPE_ID: '',
        },
        formInfo: {
          BRAND_ID: '',
          MOTOR_DISCOUNT: '',
        },
        //分页数据
        pageInfo: {
          '#LIMIT#': 1,
          '#PAGE_SIZE#': 9999,
        },
        tableDataInfo: [],
        ruleForm: {},
        options: [], //级联下拉
        motorSelect: [],
        configSetting: {},
        gridData: [],
        srcArr: [],
        brandList: [],
        info: {},
        typeId: '', //TYPE_ID
        radioId: '',
        // EQUIPMENT_ID: '',
        // value: '',
      }
    },
    created() {
      if (this.motorSelection) {
        console.log('created')
        this.motorSelection = false
      }
      this.getSelectBrandData()
      this.getTableData() //增加校验
    },
    methods: {
      rowClick(row) {
        console.log(row)
        this.radioId = row.EQUIPMENT_ID
        this.multipleTableData = row
      },
      getTableData() {
        console.log('1111', this.$store.getters['bqmsData/HeaderTable'].MOTOR_ISSUE)
        if (this.$store.getters['bqmsData/HeaderTable'].MOTOR_ISSUE == 'Y') {
          // this.disabledTable = true
          this.showData1 = true
          this.showData = false
        } else {
          // this.disabledTable = false
          this.showData1 = false
          this.showData = true
        }
      },
      //确定(模态框)
      handleShowDialog() {
        if (JSON.stringify(this.multipleTableData) != '{}') {
          let index = this.tableDataInfo.findIndex((item) => item.EQUIPMENT_ID == this.info.EQUIPMENT_ID)
          // console.log('index', index)
          // if (this.formInfo.MOTOR_DISCOUNT) {
          //   this.tableDataInfo[index].PRICE_UNTAX = this.multipleTableData[0].PRICE_UNTAX * this.formInfo.MOTOR_DISCOUNT
          // } else {
          this.tableDataInfo[index].MOTOR_NAME = this.multipleTableData.EQUIPMENT_MODEL || this.tableDataInfo[index].MOTOR_NAME
          console.log('this.tableInfo', this.tableDataInfo)
          // }
          console.log(this.formInfo)
          this.showDialog = false
          // this.gridData = []
        } else {
          this.$message({
            message: '请先选择数据！！！',
            type: 'error',
          })
        }
      },
      open() {
        this.$confirm('是否撤销发布', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.handleDialogData() //撤销发布接口
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消撤销发布',
            })
          })
      },
      //撤销发布确定
      handleDialogData() {
        this.configSetting = GFCD('bqms')
        let method = 'bqms.common.reverseRelease'
        getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify({
            DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
            TYPE: 'MOTOR_ISSUE',
          }),
        }).then((res) => {
          if (res.code == '00000') {
            this.$message({
              message: res.msg,
              type: 'success',
            })
            this.showData = true //显示发布数据
            this.showData1 = false //隐藏撤销发布
            // this.disabledTable = false
            console.log('撤销发布', res.data[method].data)
          } else {
            this.$message({ type: 'error', message: res.msg })
          }
        })
      },
      //模态框中查询
      handleQueryTable() {
        this.configSetting = GFCD('bqms')
        let method = 'bqms.motor.selection.brand.query'
        getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify({
            '#LIMIT#': 1,
            '#PAGE_SIZE#': 9999,
            BRAND_ID: this.formInfo.BRAND_ID, //品牌
            TYPE_ID: 'DJ', //写死--电机类型
          }),
        }).then((res) => {
          if (res.code == '00000') {
            this.gridData = res.data[method].data
            console.log('模态框中查询列表数据', res.data)
          } else {
            this.$message({ type: 'error', message: res.msg })
          }
        })
      },
      //查询品牌下拉数据
      getselectFormInfo() {
        this.configSetting = GFCD('bqms')
        let method = 'bqms.brand.query'
        getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify({
            '#LIMIT#': 1,
            '#PAGE_SIZE#': 9999,
            TYPE_ID: 'DJ',
          }),
        }).then((res) => {
          if (res.code == '00000') {
            this.brandList = res.data[method].data
            console.log('品牌选择下拉表格', res.data[method].data)
          } else {
            this.$message({ type: 'error', message: res.msg })
          }
        })
      },
      //查询级联下拉数据
      getSelectBrandData() {
        console.log('this.form', this.form)
        this.configSetting = GFCD('bqms')
        let method = 'bqms.type.manage.query'
        getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify({
            '#LIMIT#': 1,
            '#PAGE_SIZE#': 9999,
            TYPE: 'MOTOR_ISSUE',
            DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
          }),
        }).then((res) => {
          this.srcArr = res.data[method].data
          res.data[method].data.forEach((item) => {
            if (item.PARAENT_TYPE_ID == 0) {
              this.options.push({
                parentId: item.PARAENT_TYPE_ID,
                value: item.TYPE_ID,
                label: item.TYPE_NAME,
                children: [],
              })
            }
          })
          this.options.forEach((it) => {
            it.children = this.getChildren(it.value, this.srcArr)
          })
          console.log('options111111', this.options)
        })
      },
      // 处理级联--递归
      getChildren(tId, srcArr) {
        let children = []
        srcArr.forEach((item) => {
          if (item.PARAENT_TYPE_ID == tId) {
            children.push({
              parentId: item.PARAENT_TYPE_ID,
              value: item.TYPE_ID,
              label: item.TYPE_NAME,
              children: [],
            })
          }
        })
        if (children.length == 0) {
          return null
        }
        children.forEach((item) => {
          item.children = this.getChildren(item.value, this.srcArr)
        })
        return children
      },
      //发布数据
      handlePublishData() {
        console.log('发布数据！！！')
        this.dialogVisible = true
        this.$confirm('是否确认发布', '发布数据', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.dialogVisibleTable()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消发布',
            })
          })
      },
      handleClose() {
        this.dialogVisible = false
      },
      //确定发布数据
      dialogVisibleTable() {
        this.demo() //校验空值
      },
      //查询(通用接口)
      handleQuery() {
        if (this.form.EQUIPMENT_TYPE && this.form.EQUIPMENT_TYPE.length > 0) {
          this.typeId = this.form.EQUIPMENT_TYPE[this.form.EQUIPMENT_TYPE.length - 1]
        }
        console.log('this.form', this.form)
        this.configSetting = GFCD('bqms')
        let method = 'quotationServiceImpl.query'
        if (this.$store.getters['bqmsData/HeaderTable'].BASIC_DATA_ISSUE == 'N') return this.$message.error('基础数据未发布')
        getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify({
            '#LIMIT#': 1,
            '#PAGE_SIZE#': 9999,
            OUT_SOURCE: 'N',
            DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
            TYPE_ID: this.typeId,
            EQUIPMENT_ID: this.form.EQUIPMENT_ID,
          }),
        }).then((res) => {
          if (res.code == '00000') {
            if (res.data.length == 0) {
              this.$message({
                message: '此订单号暂无表格数据,请上传！！！',
                type: 'warning',
              })
              this.disabled = true
              // this.disabledTable = true //隐藏发布/撤销数据
              this.tableDataInfo = []
            } else {
              this.disabled = false
              this.tableDataInfo = res.data
              console.log('电机选择查询表格', res.data)
            }
          } else {
            this.$message({ type: 'error', message: res.msg })
          }
        })
      },
      //重置
      resetForm() {
        this.form.EQUIPMENT_ID = ''
        this.form.EQUIPMENT_TYPE = []
        this.formInfo = {}
        // this.options = []
        this.form.TYPE_NAME = ''
        this.form.TYPE_ID = ''
        this.typeId = ''

        //重新在请求一次查询
        this.handleQuery()
      },
      //电机选择
      handleClick(row) {
        this.info = row
        this.formInfo = {}
        this.gridData = []
        this.radioId = ''
        console.log('电机选择row', row)
        this.showDialog = true
        this.getselectFormInfo()
      },
      // 保存
      handleSure(row) {
        console.log('保存row', row)
        console.log(this.multipleTableData)
        this.configSetting = GFCD('bqms')
        let method = 'bqms.motor.selection.update'
        // this.multipleTableData.EQUIPMENT_ID
        getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify({
            DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
            ACTION: 'MOTOR_SELECT',
            EQUIPMENT_ID: row.EQUIPMENT_ID,
            MOTOR_SELECT: this.multipleTableData.EQUIPMENT_ID || row.MOTOR_SELECT,
            MOTOR_DISCOUNT: this.formInfo.MOTOR_DISCOUNT || '', //品牌折扣
          }),
        }).then((res) => {
          if (res.code == '00000') {
            this.$message({
              message: res.msg,
              type: 'success',
            })
            this.handleQuery() //再次调保存
            console.log('电机选择查询表格', res.data)
            this.$pub(`topFormData`, true)
          } else {
            this.$message({ type: 'error', message: res.msg })
          }
        })
      },
      demo() {
        let open = false
        this.tableDataInfo.forEach((item, index) => {
          console.log(item, index)
          if (this.tableDataInfo[item]) {
            open = true
          }
        })
        if (open) {
          //提示请将数据填写完成
          this.$message({
            message: '请将表格数据填写完整!!!',
            type: 'error',
          })
        } else {
          this.configSetting = GFCD('bqms')
          let method = 'bqms.common.sp.release'
          getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
            method: method,
            data: JSON.stringify({
              TYPE: 'MOTOR_ISSUE',
              DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
            }),
          }).then((res) => {
            if (res.code == '00000') {
              this.$message({
                message: res.msg,
                type: 'success',
              })
              this.dialogVisible = false
              // this.disdisabled = true
              // this.disabledTable = true
              setTimeout(() => {
                this.showData = false
                this.showData1 = true
              }, 100)
              this.$pub(`topFormData`, true)
              // this.gridData = res.data[method].data
              // console.log('电机选择查询表格', res.data[method].data)
            } else {
              this.dialogVisible = true
              this.$message({ type: 'error', message: res.msg })
            }
          })
        }
      },
    },
  })
</script>

<style lang="scss" scoped>
  .motorSelection {
    width: calc(100% - 40px);
    padding: 20px;
    background-color: #fff;

    .num_input {
      width: 210px !important;
    }
    .tip {
      width: 500px;
      height: 30px;
      line-height: 30px;
      background-color: #abcef1;
      font-size: 12px !important;
      padding-left: 14px;
      border-radius: 4px;
    }
    .num_input1 {
      width: 320px !important;
    }
  }
  // .el-table_row:hover > td {
  //   background-color: transparent !important;
  // }
  // @import '@/project/bqms/static/scss/motorSelection.sass';
</style>
